package com.virtualperson.service.impl;

import com.virtualperson.config.AliyunConfig;
import com.virtualperson.dto.*;
import com.virtualperson.exception.VideoValidationException;
import com.virtualperson.service.*;
import com.virtualperson.util.VideoValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class VideoGenerationServiceImpl implements VideoGenerationService {

    private static final String GENERATION_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2video/video-synthesis/";
    private static final String TASK_STATUS_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/{taskId}";

    @Autowired
    private AliyunConfig aliyunConfig;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private AudioProcessingService audioProcessingService;

    @Override
    public VideoGenerationResponse generateVideo(VideoGenerationRequest request) {
        try {
            // 验证请求参数
            validateRequest(request);

            // 验证图片和音频URL
            VideoValidationUtil.validateImage(request.getInput().getImage_url());
            VideoValidationUtil.validateAudio(request.getInput().getAudio_url());

            // 获取音频时长
            float audioDuration = audioProcessingService.getAudioDuration(
                request.getInput().getAudio_url());

            // 设置音频时长
            request.getParameters().setDuration(audioDuration);

            // 发送请求
            return processVideoGeneration(request);

        } catch (Exception e) {
            log.error("视频生成请求失败", e);
            throw new VideoValidationException("视频生成请求失败: " + e.getMessage());
        }
    }

    private VideoGenerationResponse processVideoGeneration(VideoGenerationRequest request) {
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aliyunConfig.getApiKey());
            headers.set("X-DashScope-Async", "enable");

            // 发送请求
            HttpEntity<VideoGenerationRequest> entity = new HttpEntity<>(request, headers);
            ResponseEntity<VideoGenerationResponse> response = restTemplate.exchange(
                GENERATION_URL,
                HttpMethod.POST,
                entity,
                VideoGenerationResponse.class
            );

            VideoGenerationResponse result = response.getBody();
            if (result == null) {
                throw new VideoValidationException("视频生成服务返回空响应");
            }

            log.info("视频生成请求成功，taskId: {}", result.getOutput().getTaskId());
            return result;

        } catch (Exception e) {
            log.error("处理视频生成失败", e);
            throw new VideoValidationException("处理视频生成失败: " + e.getMessage());
        }
    }

    @Override
    public VideoGenerationResponse getTaskStatus(String taskId) {
        try {
            if (!StringUtils.hasText(taskId)) {
                throw new VideoValidationException("任务ID不能为空");
            }

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + aliyunConfig.getApiKey());

            // 发送请求
            HttpEntity<?> entity = new HttpEntity<>(headers);
            ResponseEntity<VideoGenerationResponse> response = restTemplate.exchange(
                TASK_STATUS_URL.replace("{taskId}", taskId),
                HttpMethod.GET,
                entity,
                VideoGenerationResponse.class
            );

            VideoGenerationResponse result = response.getBody();
            if (result == null) {
                throw new VideoValidationException("获取任务状态返回空响应");
            }

            log.info("获取任务状态成功，taskId: {}, status: {}", taskId, result.getOutput().getTaskStatus());
            return result;

        } catch (Exception e) {
            log.error("获取任务状态失败", e);
            throw new VideoValidationException("获取任务状态失败: " + e.getMessage());
        }
    }

    private void validateRequest(VideoGenerationRequest request) {
        if (request == null) {
            throw new VideoValidationException("请求参数不能为空");
        }

        if (!"liveportrait".equals(request.getModel())) {
            throw new VideoValidationException("model参数必须为liveportrait");
        }

        if (request.getInput() == null) {
            throw new VideoValidationException("input参数不能为空");
        }

        if (!StringUtils.hasText(request.getInput().getImage_url())) {
            throw new VideoValidationException("image_url参数不能为空");
        }

        if (!StringUtils.hasText(request.getInput().getAudio_url())) {
            throw new VideoValidationException("audio_url参数不能为空");
        }

        // 验证参数
        if (request.getParameters() != null) {
            // 验证模板ID
            if (request.getParameters().getTemplate_id() != null &&
                !isValidTemplateId(request.getParameters().getTemplate_id())) {
                throw new VideoValidationException("无效的template_id，必须是normal、calm或active");
            }

            // 验证视频时长
            Float duration = request.getParameters().getDuration();
            if (duration == null) {
                throw new VideoValidationException("视频时长不能为空");
            }
            if (duration < 1.0f || duration > 300.0f) {
                throw new VideoValidationException("视频时长必须在1-300秒范围内");
            }

            // 验证音量
            Integer volume = request.getParameters().getVolume();
            if (volume != null && (volume < 0 || volume > 100)) {
                throw new VideoValidationException("音量必须在0-100范围内");
            }
        } else {
            throw new VideoValidationException("parameters参数不能为空");
        }
    }

    private boolean isValidTemplateId(String templateId) {
        return "normal".equals(templateId) || 
               "calm".equals(templateId) || 
               "active".equals(templateId);
    }
} 